#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Modify DemandServiceImpl.java to add enhanced logging for AI response diagnosis
"""

import shutil
import sys

# Set console encoding to UTF-8 for Windows
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

file_path = r"C:\Users\lyc\Desktop\spb\src\main\java\com\expert\miniapp\service\impl\DemandServiceImpl.java"

# Create backup
backup_path = file_path + ".backup"
shutil.copy2(file_path, backup_path)
print(f"[OK] Created backup: {backup_path}")

# Read the file
with open(file_path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

# Find the section to replace (lines 165-184, but in 0-index it's 164-183)
start_line = 164  # Line 165 in file (0-indexed)
end_line = 183    # Line 184 in file (0-indexed)

# New code to insert
new_code = """        String content;
        String responseBody = "";
        try {
            logger.info("=== 开始调用AI匹配接口 ===");
            logger.info("请求URL: {}", aiConfig.getUrl());
            logger.info("请求payload长度: {} 字符", payloadJson.length());

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
            responseBody = response.body();

            logger.info("=== AI响应诊断信息 ===");
            logger.info("HTTP状态码: {}", response.statusCode());
            logger.info("响应body长度: {} 字符", responseBody != null ? responseBody.length() : 0);
            logger.info("响应body前500字符: {}", responseBody != null && responseBody.length() > 0 ?
                responseBody.substring(0, Math.min(500, responseBody.length())) : "空响应");

            if (response.statusCode() < 200 || response.statusCode() >= 300) {
                logger.error("AI接口返回非2xx状态码: {}, 响应body: {}", response.statusCode(), responseBody);
                throw new RuntimeException("AI匹配接口返回非2xx状态: " + response.statusCode());
            }

            var root = objectMapper.readTree(responseBody);
            logger.info("JSON解析成功");

            var choices = root.path("choices");
            logger.info("choices节点是否存在: {}", !choices.isMissingNode());
            logger.info("choices是否为数组: {}", choices.isArray());
            logger.info("choices数组大小: {}", choices.isArray() ? choices.size() : 0);

            if (!choices.isArray() || choices.isEmpty()) {
                logger.error("AI响应中choices字段无效, 完整响应: {}", responseBody);
                throw new RuntimeException("AI匹配未取得推荐请求采用数据");
            }

            content = choices.get(0).path("message").path("content").asText("");
            logger.info("提取到的content长度: {} 字符", content.length());
            logger.info("content前200字符: {}", content.length() > 0 ?
                content.substring(0, Math.min(200, content.length())) : "空内容");

        } catch (Exception e) {
            logger.error("AI匹配调用失败: {}", e.getMessage(), e);
            logger.error("失败时的响应body: {}", responseBody);
            throw new RuntimeException("AI匹配调用失败: " + e.getMessage(), e);
        }

        if (!StringUtils.hasText(content)) {
            logger.error("AI返回的content为空字符串! 完整响应body: {}", responseBody);
            throw new RuntimeException("AI匹配未返回内容");
        }
"""

# Build new file content
new_lines = []
new_lines.extend(lines[:start_line])  # Lines before modification
new_lines.append(new_code)            # Insert new code
new_lines.extend(lines[end_line+1:])  # Lines after modification

# Write back
with open(file_path, 'w', encoding='utf-8') as f:
    f.writelines(new_lines)

print(f"[OK] Modification completed!")
print(f"[OK] Modified lines {start_line+1}-{end_line+1} with detailed logging")
print(f"[OK] Original file backed up to: {backup_path}")
print("\nPlease restart Spring Boot application for changes to take effect")
